package com.hoyue.dao.impl;

import com.hoyue.bean.Info;
import com.hoyue.bean.MessageBoard;
import com.hoyue.dao.MessageBoardDao;
import com.hoyue.service.MessageBoardService;
import com.hoyue.utils.C3P0Utils;
import com.hoyue.utils.Page;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class MessageBoardDaoImpl extends PageDaoImpl<MessageBoard> implements MessageBoardDao {
    // 获取queryrunner对象
    QueryRunner qr = C3P0Utils.getQueryRunner();

    @Override
    public List<MessageBoard> getAllMessageBoard() throws SQLException {
        String sql = "SELECT * FROM message_board";
        return qr.query(sql,new BeanListHandler<>(MessageBoard.class));
    }

    @Override
    public void addMessageBoard(MessageBoard messageBoard) throws SQLException {
        String sql = "INSERT INTO message_board (name,email,phone,message) VALUES (?,?,?,?)";

        Object[] params = new Object[4];

        params[0] = messageBoard.getName();
        params[1] = messageBoard.getEmail();
        params[2] = messageBoard.getPhone();
        params[3] = messageBoard.getMessage();

        qr.update(sql,params);
    }

    @Override
    public void deleteMessageBoard(int id) throws SQLException {
        String sql = "DELETE FROM message_board where id=?";

        qr.update(sql,id);
    }

    @Override
    public void updateMessageBoard(MessageBoard messageBoard) throws SQLException {
        String sql = "UPDATE message_board SET name=?, email=?, phone=?, message=? WHERE id=?";

        qr.update(sql,messageBoard.getName(),messageBoard.getEmail(),messageBoard.getPhone(),messageBoard.getMessage());
    }

    @Override
    public void deleteMessageBoards(String ids) throws SQLException {

        String[] idArr = ids.split(","); //拆分id
        String sql = "DELETE FROM message_board where id=?";
        for(int i = 0; i < idArr.length; i ++) {
            qr.update(sql,Integer.parseInt(idArr[i]));
        }
    }

    @Override
    public Page<MessageBoard> getPage(int page, String tableName) throws SQLException {
        Page<MessageBoard> message =  getListByPage(page,tableName);

        return message;
    }
}
